package com.zbkj.crmeb.task.plat.poizon;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.RestTemplateConfig;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.factory.TaskParamsDto;
import com.factory.TaskProcessEngineFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.by.service.PlatProductService;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.Relation;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonResponseBodyDto;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonUpdateStocksAndPricesDto;
import com.zbkj.crmeb.task.plat.poizon.dto.ToizonLoginUserDto;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 得物捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("poizonProductTask")
@Configuration
@Slf4j
public class PoizonProductTask extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(PoizonProductTask.class);

    @Resource
    private PlatProductService platProductService;

    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("poizonOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;
    @Autowired
    PoizonApi poizonApi;
    @Autowired
    Redisson redisson;

    private static final String LOCK_KEY = "poizonProductTask";


    private static String envValue;
    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        envValue = env;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        if (Objects.equals(envValue,"test")||Objects.equals(envValue,"dev")){
//            log.info("当前环境暂不推送商品, env:{}",envValue);
//            return;
//        }
//        // 整个线程轮询
//        new Thread(()->{
//            RLock rLock = redisson.getLock(LOCK_KEY);
//            while (true){
//                try {
//                    if (!rLock.tryLock(3, TimeUnit.SECONDS)) {
//                        log.warn("未获取到锁，稍后尝试");
//                        continue;
//                    }
//                    TaskProcessEngineFactory.executeTask();
////                    checkByProductStockV2();
////                    checkByProductPriceV2();
//                    Thread.sleep(RandomUtils.nextInt(1000, 3000));
//                } catch (Exception e) {
//                    log.error("商品轮询任务执行失败");
//                } finally {
//                    rLock.unlock();
//                }
//            }
//        }).start();
    }

    @Override
    public Result execute(TaskParamsDto taskParamsDto) {
        // mock个请求
        MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
        mockHttpServletRequest.addHeader("mer_id", String.valueOf(taskParamsDto.getMerId()));
        ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
        RequestContextHolder.setRequestAttributes(servletRequestAttributes);
        CommonResult<List<String>> commonResult = null;
        try {
            taskParamsDto.getPlatProductRequest().setSyncTask(false);
            commonResult = platProductService.pushProduct(taskParamsDto.getPlatProductRequest(), Integer.valueOf(StringUtils.isNotBlank(taskParamsDto.getMerId()) ? taskParamsDto.getMerId() : MerPlatEnums.BY_126.getMerId().toString()));
            if (commonResult.getCode() == ExceptionCodeEnum.SUCCESS.getCode()) {
                return Result.getSuccessResult();
            }
            if (commonResult.getCode() != ExceptionCodeEnum.SUCCESS.getCode()) {
//            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"推送商品失败,productId:+"+taskParamsDto.getPlatProductRequest().getProductId()+",:"+commonResult.getMessage());
                log.error("推送商品失败,productId:{},:{}", taskParamsDto.getPlatProductRequest().getProductId(), commonResult.getMessage());
            }
        } catch (Exception e) {
            logger.error("推送商品失败,查询商品异常:", e);
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
        return Result.getFailureResult("execute error", commonResult.getMessage());
    }

    @XxlJob("checkPoizonProductPrice")
    public void checkByProductPriceV2() {
        List<Integer> merIds = new ArrayList<>();
        merIds.add(MerPlatEnums.POIZON_142.getMerId());
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (Objects.equals(merId, MerPlatEnums.POIZON_142.getMerId())) {
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DW;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_DW;
                checkPoizonProductPrice(merId, productRelationsType, skuRelationsType);
            }
        }
    }

    public void checkPoizonProductPrice(Integer merId, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        try {
            // mock个请求
            MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
            mockHttpServletRequest.addHeader("mer_id", String.valueOf(merId));
            ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            // 捞上架数据
            int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, PlatPushStatusEnums.DW_UP.getCode()).eq(Relation::getBusinessType, productRelationsType.getCode()));
            if (count == 0) {
                logger.error("得物商家商品检查任务,未扫描到已上架商品");
                return;
            }
            // 需要更新价格sku
            List<StoreProductAttrValue> needUpdateSkus = new ArrayList<>();
            int maxPage = (count + 499) / 500;
            int pageNo = 1;
            while (pageNo <= maxPage) {
                Page<Relation> page = PageHelper.startPage(pageNo, 500);
                try {
                    relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, PlatPushStatusEnums.DW_UP.getCode()).eq(Relation::getBusinessType, productRelationsType.getCode()).orderByDesc(Relation::getId));
                    List<Relation> productRelations = page.getResult();
                    if (CollectionUtils.isEmpty(productRelations)) {
                        throw new RuntimeException("数据查询异常");
                    }
                    // 检查sku信息
                    List<Integer> productIds = productRelations.stream().map(k -> Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());
                    List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                    if (CollectionUtils.isEmpty(attrValues)) {
                        continue;
                    }
                    Map<Integer, List<StoreProductAttrValue>> skuMap = attrValues.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
                    List<StoreProduct> storeProducts = storeProductService.listByIds(productIds);
                    Map<Integer, StoreProduct> productMap = storeProducts.stream().collect(Collectors.toMap(StoreProduct::getId, v -> v));
                    Map<Integer, Relation> productRelationMap = productRelations.stream().collect(Collectors.toMap(k -> Integer.valueOf(k.getBusinessCode()), v -> v));
                    for (Map.Entry<Integer, List<StoreProductAttrValue>> entry : skuMap.entrySet()) {
                        Integer productId = entry.getKey();
                        List<StoreProductAttrValue> skus = entry.getValue();
                        StoreProduct storeProduct = productMap.get(productId);
                        Relation relation = productRelationMap.get(productId);
                        if (CollectionUtils.isEmpty(skus) || null == storeProduct) {
                            continue;
                        }
                        priceUtil.calcProductValuePrice(skus, merId, storeProduct, AreaTypeEnum.ABROAD.getType(), null, false, null, true, null);
                        // 过滤需要更新价格的sku
                        List<StoreProductAttrValue> needUpdatePriceList = needUpdatePriceProducts(skus, relation, productRelationsType, skuRelationsType);
                        if (CollectionUtils.isNotEmpty(needUpdatePriceList)) {
                            needUpdateSkus.addAll(needUpdatePriceList);
                        }

                    }
                } catch (Exception e) {
                    logger.error("得物商家商品价格检查任务,查询商品异常", e);
                } finally {
                    pageNo++;
                }
            }
            if (CollectionUtils.isNotEmpty(needUpdateSkus)) {
                doUpdateSkusPrice(needUpdateSkus);
            }
        } catch (Exception e) {
            logger.error("得物商家商品价格检查任务,查询商品异常:", e);
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }


    }

    private void doUpdateSkusPrice(List<StoreProductAttrValue> updateSkus) {
        try {
            for (StoreProductAttrValue skus : updateSkus) {
                String srcPrice = skus.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE);
                String merchantProductId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID);
                String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
                String salePrice = skus.getPushRelation().getFeature(ByCommonConstant.NEW_PLAT_SALE_PRICE);
                String price = skus.getPushRelation().getFeature(ByCommonConstant.NEW_PLAT_ORIGINAL_PRICE);

                PoizonUpdateStocksAndPricesDto dto = new PoizonUpdateStocksAndPricesDto();
                List<PoizonUpdateStocksAndPricesDto.Sku> skuList = new ArrayList<>();
                PoizonUpdateStocksAndPricesDto.Sku sku = new PoizonUpdateStocksAndPricesDto.Sku();
                sku.setSpuId(merchantProductId);
                sku.setSkuId(skuId);
                sku.setRetailPrice(salePrice);
                sku.setPurchasePrice(price);
                skuList.add(sku);
                dto.setSkuList(skuList);
                // 随机休眠一下，下次做下限流
                Thread.sleep(RandomUtils.nextInt(10, 100));
                PoizonResponseBodyDto<PoizonResponseBodyDto.UpdateStocksAndPricesDataDTO> responseBodyDto = poizonApi.updateStocksAndPrices(dto);

                if (responseBodyDto.getStatus() == 200 && responseBodyDto.getData().getUpdateResult() && responseBodyDto.getData().getFailList().isEmpty()) {
                    skus.getPushRelation().addFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE, String.valueOf(sku.getRetailPrice()));
                    relationService.updateById(skus.getPushRelation());
                }
//                DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,String.format("得物更新价格，原价:%s ,更新价格:%s ,接口返回:%s",srcPrice,price,post));
                logger.error("得物更新价格，原价:{} ,更新价格:{} ,接口返回:{}", srcPrice, price, JSON.toJSONString(responseBodyDto));
            }
        } catch (Exception e) {
            log.error("更新sku价格异常:", e);
        }
    }

    private List<StoreProductAttrValue> needUpdatePriceProducts(List<StoreProductAttrValue> attrValues, Relation relation, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        // 移除掉库存为0
        attrValues.removeIf(k -> k.getStock() <= 0);
        if (CollectionUtils.isEmpty(attrValues)) {
            return null;
        }
        // 金额加上一二段费用
        attrValues.forEach(v -> v.setPrice(getValidPrice(v.getPrice()).add(getValidPrice(v.getFirstPrice())).add(getValidPrice(v.getSecondPrice()))));
        // 库存>0且价格最低的sku
        Map<String, StoreProductAttrValue> sortMap = attrValues.stream().filter(k -> k.getStock() > 0).collect(Collectors.toMap(StoreProductAttrValue::getSuk, v -> v, (v1, v2) -> {
            if (v1.getPrice().compareTo(v2.getPrice()) <= 0) {
                return v1;
            }
            return v2;
        }));
        // 获取上架的sku
        List<StoreProductAttrValue> srcSkus = storeProductAttrValueService.listRelationInfoByProductId(Collections.singletonList(Integer.valueOf(relation.getBusinessCode())), skuRelationsType);
        // 移除掉没有推送关联或者未上架的sku
        srcSkus.removeIf(k -> null == k.getPushRelation() || !Objects.equals(k.getPushRelation().getSubCode(), PlatPushStatusEnums.DW_UP.getCode()));
        if (CollectionUtils.isEmpty(srcSkus)) {
            return null;
        }
        List<StoreProductAttrValue> needUpdateList = new ArrayList<>();
        // 获取最终需要更新的数据
        for (StoreProductAttrValue srcSku : srcSkus) {
            String suk = srcSku.getSuk();
            // 用规格来匹配
            if (!sortMap.containsKey(suk)) {
                continue;
            }
            StoreProductAttrValue sku = sortMap.get(suk);
            BigDecimal baseExchange = new BigDecimal("7.0");
            MoneyExchange moneyExchange = moneyExchangeService.getById(11);
            if (null != moneyExchange && StringUtils.isNotBlank(moneyExchange.getBankConversionPri())) {
                baseExchange = new BigDecimal(moneyExchange.getBankConversionPri());
            }
            // 平台原价为空或者差价绝对值超过了固定点
            boolean flag = StringUtils.isBlank(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE)) || outPriceThreshold(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE), sku.getPrice(), baseExchange);
            if (flag) {
                BigDecimal purchasePrice = sku.getPrice().divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN);
                srcSku.getPushRelation().addFeature(ByCommonConstant.NEW_PLAT_ORIGINAL_PRICE, purchasePrice.toString());
                srcSku.getPushRelation().addFeature(ByCommonConstant.NEW_PLAT_SALE_PRICE, purchasePrice.add(sku.getTaxPrice()).toString());
                srcSku.getPushRelation().addFeature(ByCommonConstant.MERCHANT_PRODUCT_ID, relation.getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID));
                srcSku.getPushRelation().addFeature(ByCommonConstant.PUSH_PRICE, String.valueOf(sku.getPrice()));
                needUpdateList.add(srcSku);
            }
        }
        return needUpdateList;
    }

    private boolean outPriceThreshold(String platPrice, BigDecimal price, BigDecimal baseExchange) {
        String newPrice = String.valueOf(price.divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue());
        // 最大差值
        double maxDiff = new BigDecimal(platPrice).multiply(new BigDecimal("0.02")).doubleValue();
        return Math.abs(Integer.parseInt(newPrice) - Integer.parseInt(platPrice)) > maxDiff;
    }

    private BigDecimal getValidPrice(BigDecimal value) {
        return null == value || value.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : value;
    }

    @XxlJob("checkPoizonProductStock")
    public void checkByProductStockV2() {
        List<Integer> merIds = new ArrayList<>();
        merIds.add(MerPlatEnums.POIZON_142.getMerId());
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (Objects.equals(merId, MerPlatEnums.POIZON_142.getMerId())) {
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DW;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_DW;
                checkByProductStock(merId, productRelationsType, skuRelationsType);
            }
        }
    }

    public void checkByProductStock(Integer merId, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        // 捞上架数据
        int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, PlatPushStatusEnums.DW_UP.getCode()).eq(Relation::getBusinessType, productRelationsType.getCode()));
        if (count == 0) {
            logger.error("得物商家商品检查任务,未扫描到已上架商品");
            return;
        }
        int maxPage = (count + 499) / 500;
        int pageNo = 1;
        while (pageNo <= maxPage) {
            Page<Relation> page = PageHelper.startPage(pageNo, 500);
            try {
                relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, PlatPushStatusEnums.DW_UP.getCode()).eq(Relation::getBusinessType, productRelationsType.getCode()).orderByDesc(Relation::getId));
                List<Relation> productRelations = page.getResult();
                if (CollectionUtils.isEmpty(productRelations)) {
                    throw new RuntimeException("数据查询异常");
                }
                // 检查sku信息
                List<Integer> productIds = productRelations.stream().map(k -> Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());

                List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                if (CollectionUtils.isEmpty(attrValues)) {
                    throw new RuntimeException("SKU数据为空");
                }
                Map<Integer, List<StoreProductAttrValue>> map = filterSkuInfos(attrValues);
                if (MapUtils.isEmpty(map)) {
                    continue;
                }
                for (Relation relation : productRelations) {
                    Integer productId = Integer.valueOf(relation.getBusinessCode());
                    if (!map.containsKey(productId)) {
                        continue;
                    }
                    List<StoreProductAttrValue> storeProductAttrValues = map.get(productId);
                    updateProduct(relation.getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID), storeProductAttrValues);
                }
            } catch (Exception e) {
                logger.error("得物商家商品检查任务,查询商品异常", e);
            } finally {
                pageNo++;
            }
        }
    }

    private void updateProduct(String merchantProductId, List<StoreProductAttrValue> storeProductAttrValues) {
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return;
        }
        List<StoreProductAttrValue> downSkus = new ArrayList<>();
        List<StoreProductAttrValue> updateSkus = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            if (storeProductAttrValue.getStock() <= 0) {
                downSkus.add(storeProductAttrValue);
                continue;
            }
            updateSkus.add(storeProductAttrValue);
        }
        try {
            if (CollectionUtils.isNotEmpty(downSkus)) {
                doDownSkus(merchantProductId, downSkus);
            }
        } catch (Exception e) {
            logger.error("商品下架异常:", e);
        }
        try {
            if (CollectionUtils.isNotEmpty(updateSkus)) {
                doUpdateSkus(merchantProductId, updateSkus);
            }
        } catch (Exception e) {
            logger.error("更新商品库存异常:", e);
        }

    }

    private void doUpdateSkus(String merchantProductId, List<StoreProductAttrValue> updateSkus) {
        for (StoreProductAttrValue skus : updateSkus) {
            try {
                Thread.sleep(RandomUtils.nextInt(10, 100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
            PoizonUpdateStocksAndPricesDto dto = new PoizonUpdateStocksAndPricesDto();
            List<PoizonUpdateStocksAndPricesDto.Sku> skuList = new ArrayList<>();
            PoizonUpdateStocksAndPricesDto.Sku sku = new PoizonUpdateStocksAndPricesDto.Sku();
            sku.setSpuId(merchantProductId);
            sku.setSkuId(skuId);
            sku.setStock(skus.getStock());
            skuList.add(sku);
            dto.setSkuList(skuList);
            PoizonResponseBodyDto<PoizonResponseBodyDto.UpdateStocksAndPricesDataDTO> responseBodyDto = poizonApi.updateStocksAndPrices(dto);
            if (responseBodyDto.getStatus() == 200 && responseBodyDto.getData().getUpdateResult() && responseBodyDto.getData().getFailList().isEmpty()) {
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK, String.valueOf(skus.getStock()));
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.DW_UP.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "得物更新库存返回:" + JSON.toJSON(responseBodyDto));
            logger.error("得物更新库存返回:{}", JSON.toJSON(responseBodyDto));
        }

    }

    private void doDownSkus(String merchantProductId, List<StoreProductAttrValue> downSkus) {
        for (StoreProductAttrValue skus : downSkus) {
            try {
                Thread.sleep(RandomUtils.nextInt(10, 100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
            PoizonUpdateStocksAndPricesDto dto = new PoizonUpdateStocksAndPricesDto();
            List<PoizonUpdateStocksAndPricesDto.Sku> skuList = new ArrayList<>();
            PoizonUpdateStocksAndPricesDto.Sku sku = new PoizonUpdateStocksAndPricesDto.Sku();
            sku.setSpuId(merchantProductId);
            sku.setSkuId(skuId);
            sku.setStock(ByCommonConstant.ZERO);
            dto.setSkuList(skuList);
            PoizonResponseBodyDto<PoizonResponseBodyDto.UpdateStocksAndPricesDataDTO> responseBodyDto = poizonApi.updateStocksAndPrices(dto);
            if (responseBodyDto.getStatus() == 200 && responseBodyDto.getData().getUpdateResult() && responseBodyDto.getData().getFailList().isEmpty()) {
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK, "0");
                skus.getPushRelation().addFeature(ByCommonConstant.PUSH_PLAT, "N");
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.DW_DOWN.getCode());
                relationService.updateById(skus.getPushRelation());
            }

            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "得物sku下架返回:" + JSON.toJSONString(responseBodyDto));
            logger.error("得物sku下架返回:{}", JSON.toJSONString(responseBodyDto));
        }

    }


    private Map<Integer, List<StoreProductAttrValue>> filterSkuInfos(List<StoreProductAttrValue> attrValues) {
        Iterator<StoreProductAttrValue> iterator = attrValues.iterator();
        Map<Integer, List<StoreProductAttrValue>> map = new HashMap<>();
        while (iterator.hasNext()) {
            StoreProductAttrValue attrValue = iterator.next();
            // 没有推送关系，没有上架标记，库存大于0并且上架库存和当前库存相等
            boolean flag = attrValue.getPushRelation() == null || !Objects.equals(attrValue.getPushRelation().getSubCode(), PlatPushStatusEnums.DW_UP.getCode()) || (Objects.equals(attrValue.getStock(), Integer.valueOf(attrValue.getPushRelation().getFeature(ByCommonConstant.ORIGIN_STOCK))));
            if (flag) {
                iterator.remove();
                continue;
            }
            map.computeIfAbsent(attrValue.getProductId(), v -> new ArrayList<>()).add(attrValue);
        }
        return map;
    }

}
